<template>
  <div class="role-manage">
    <div class="query-form">
      <el-form ref="form" :inline="true" :model="roleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="resetFields">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="action">
        <el-button type="primary" @click="handleAdd">创建</el-button>
      </div>
      <el-table :data="roleList">
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :formatter="item.formatter"
        >
        </el-table-column>
        <el-table-column label="操作" width="260">
          <template #default="scope">
            <el-button size="default" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="default"
              @click="openPermission(scope.row)"
              type="primary"
              >设置权限</el-button
            >
            <el-button
              type="danger"
              size="default"
              @click="handleDel(scope.row._id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 角色新建和编辑 -->
    <el-dialog title="用户新增" v-model="showModal">
      <el-form
        ref="dialogForm"
        :model="roleForm"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :rows="2"
            v-model="roleForm.remark"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 权限弹窗 -->
    <el-dialog title="权限设置" v-model="permissionModal">
      <el-form label-width="100px">
        <el-form-item label="角色名称">
          {{ roleName }}
        </el-form-item>
        <el-form-item label="权限设置">
          <!-- props设置是tree组件显示的文本内容
          default-expand-all 控制默认展开
           -->
          <el-tree
            ref="tree"
            :data="menuList"
            :props="{ label: 'menuName' }"
            node-key="_id"
            show-checkbox
            default-expand-all
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button>取 消</el-button>
          <el-button type="primary" @click="permissionSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 制作权限分配的流程：
// step1 制作对应的弹窗并且把菜单数据渲染道弹窗中
import storage from "../utils/storage.js";
import api from "../api/index";
import { ref, reactive, nextTick, toRaw } from "vue";
import utils from "../utils/utils";

// 定义查询事件
const onSubmit = async () => {
  let res = await api.getRoleAllList(roleForm);
  roleList.value = res.list;
};
//定义选中的角色id
const roleId = ref("");
//定义显示的roleName
const roleName = ref("");
//定义弹窗变量
const permissionModal = ref(false);
//定义打开权限弹窗方法
const openPermission = (row) => {
  permissionModal.value = true;
  console.log(row);
  roleId.value = row._id;
  roleName.value = row.roleName;
  //先把对象中的权限列表解构出来
  // checkedKeys 数组 是存放选中节点的id
  let { checkedKeys } = row.permissionList;
  //使用setCheckKey去把id赋值到tree控件中，显示对应的权限
  setTimeout(() => {
    // 用setCheckKey是tree节点的方法
    //获取节点mounted 确保节点一定获取了
    tree.value.setCheckedKeys(checkedKeys);
  });
};
//定义获取tree节点
const tree = ref(null);
//定义菜单列表
const menuList = ref([]);
//定义获取菜单请求方法
const getMenuList = async () => {
  let list = await api.getMenuList();
  menuList.value = list;
};
getMenuList();
//定义菜单映射表 {'dfdfd':'菜单管理'}
let actionMap = reactive({});
//定义建立映射表的方法
const getActionMap = (list) => {
  //list是请求过来的数据
  let map = {};
  const deep = (arr) => {
    while (arr.length) {
      let item = arr.pop();
      //item就代表了每个对象 一级菜单
      if (item.children && item.action) {
        // 二级菜单
        map[item._id] = item.menuName;
      }
      if (item.children && !item.action) {
        //一级菜单
        deep(item.children);
      }
    }
  };
  deep(JSON.parse(JSON.stringify(list)));
  // console.log(map);
  actionMap = map;
};

getActionMap(storage.getItem("menuList"));

//定义权限弹窗中的提交事件
const permissionSubmit = async () => {
  //id是角色的Id=》可以从上面row对象中获取
  //如何获取选中的checkedKeys =[]
  let nodes = tree.value.getCheckedNodes();
  console.log(nodes);
  //如何获取选中的halfCheckedKeys = []
  let halfCheck = tree.value.getHalfCheckedKeys();
  console.log(halfCheck);
  let parentKeys = []; //存放选中的元素的父节点id
  let checkedKeys = []; //存放选中的元素的节点id
  nodes.forEach(async (node) => {
    //判断选中的是不是按钮，还是菜单
    if (!node.children) {
      //说明是按钮
      checkedKeys.push(node._id);
    } else {
      //说明是菜单
      parentKeys.push(node._id);
    }
  });
  console.log(checkedKeys, parentKeys);
  let halfCheckedKeys = parentKeys.concat(halfCheck);
  let data = {
    _id: roleId.value,
    permissionList: {
      checkedKeys,
      halfCheckedKeys,
    },
  };
  //发请求，
  await api.updatePermission(data);
  //关闭弹窗
  permissionModal.value = false;
  //设置权限成功提示
  //刷新角色数据
  getRoleAllList();
};

//定义用户行为初始化
const action = ref("add");
//定义校验规则
const rules = reactive({
  roleName: [
    {
      required: true,
      message: "请输入角色角色名称",
    },
  ],
});
//定义dialogForm节点
const dialogForm = ref(null);
//定义角色列表
const roleList = ref([]);
//定义新增模块用户
let roleForm = reactive({});
//定义弹窗
const showMadol = ref(false);
//定义动态表格--格式
const columns = reactive([
  {
    label: "角色名称",
    prop: "roleName",
  },
  {
    label: "备注",
    prop: "remark",
  },
  {
    label: "权限列表",
    prop: "permissionList",
    width: 200,
    formatter: (row, column, value) => {
      //显示的数组
      let names = [];
      let halfKeys = value.halfCheckedKeys || [];
      //当前对象的权限id
      //去查找actionMap
      halfKeys.map((key) => {
        let name = actionMap[key];
        if (key && name) {
          names.push(name);
        }
      });
      // console.log(names);
      return names.join(",");
    },
  },
]);

//定义用户列表
const userList = ref([]);
const showModal = ref(false);
// 定义编辑事件
const handleEdit = (row) => {
  action.value = "edit";
  showModal.value = true;
  nextTick(() => {
    Object.assign(roleForm, row);
  });
};

//获取角色列表
const getRoleAllList = async () => {
  let { list, page } = await api.getRoleAllList();
  roleList.value = list;
};
//管理页面数据初始化请求
getRoleAllList();
//定义弹窗取消事件
const handleCancel = () => {
  resetForm();
  showMadol.value = !showMadol.value;
};

//重置表单事件
const resetForm = () => {
  dialogForm.value.resetFields();
};
//定义编辑事件
const edit = (row) => {
  action.value = "edit";
  showMadol.value = !showMadol.value;
  nextTick(() => {
    Object.assign(roleForm, row);
  });
};
const handleDel = async (_id) => {
  await api.roleOperate({ _id, action: "delete" });
  getRoleAllList();
};
// 角色添加
const handleAdd = () => {
  action.value = "create";
  showModal.value = true;
};
// 定义创建事件
const handleSubmit = () => {
  // console.log(roleForm);
  dialogForm.value.validate(async (vaild) => {
    if (vaild) {
      let data = toRaw(roleForm);
      console.log(roleForm);
      data.action = action.value;
      let res = await api.roleOperate(data);

      getRoleAllList();
      showModal.value = false;
      console.log(showModal.value);
      resetForm();
    }
  });
};
</script>

<style lang="scss" scoped></style>
